//
//  AppDelegate.m
//  Syndesis
//
//  Created by yinda on 2018/8/29.
//  Copyright © 2019年 Jinfeng. All rights reserved.
//

#import "AppDelegate.h"
//极光推送
static NSString *key_JPush = @"5a4793eb0a30ec769c8facbb";
#ifdef DEBUG
#define IS_PRODUCTION NO // 0 (默认值)表示采用的是开发证书，即测试环境
#define CHANNEL @"debug"
#else
#define IS_PRODUCTION YES // 1 表示采用生产证书,即生产环境
#define CHANNEL @"app store"
#endif
#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h> // 这里是iOS10需要用到的框架
#endif
#import "AFNetworkActivityIndicatorManager.h"

@interface AppDelegate ()<JPUSHRegisterDelegate,UIAlertViewDelegate>{
    UILabel *_infoLabel;
    UILabel *_tokenLabel;
    UILabel *_udidLabel;
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //网络初始化
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

    // 初始化推送(JPush)
    [self initJpush:application didFinishLaunchingWithOptions:launchOptions];
    
    // 初始化UI
//    [self initUI];
    
    // 初始化默认语言
    [self initLanguage];
    [self Checkforupdates];
    
    return YES;
}

//推到后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
    //    [application setApplicationIconBadgeNumber:0];
    NSLog(@"程序进入后台");
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    //取消所有通知
    //    [application setApplicationIconBadgeNumber:0];
    //    [application cancelAllLocalNotifications];
}

//进到前台
- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    //判断是否需要刷新头像图片
    [THMangerTool setUpHeadDateTime:NO];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    NSLog(@"收到本地通知回到");
    
}

#pragma  mark- 初始化默认语言
- (void)initLanguage {
    // 如果是默认语言根据系统语言设置语言
    if ([THMangerTool getLanageType] == NSLanguageDefault) {
        [UtilCheck setLanguage:[THMangerTool getPreferredLanguage]];
    }
    else {
        [UtilCheck setLanguage:[THMangerTool getLanageType]];
    }
    
}

#pragma mark - 初始化 UI
- (void)initUI {
    
    //导航栏 状态栏
    {
        /*
         ================
         启动隐藏状态栏 运行隐藏状态栏 首先要在plist 中设置key Status bar is initially hidden 设置YES
         ================
         */
        //   [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
        //启动是是否隐藏状态栏
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        
        /*
         ================
         统一导航颜色
         ================
         */
        //X色导航 NavigationControllerImageByColor
        [[UINavigationBar appearance] setBackgroundImage:[UtilCheck NavigationControllerImageByColor: SYSTEM_COLOR] forBarMetrics:UIBarMetricsDefault];
        
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window setBackgroundColor:[UtilCheck hexStringToColor:myBackColor alpha:1]];
    // 设置首页
//    [self setUpMainViewControllerOrLoginViewController:NO];
}


// ios9.0 之后用这个方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
    
    if ([url.host isEqualToString:@"BoDenTech.BJ"])
    {
        
        return  [[UIApplication sharedApplication] openURL:url];
    }
    return YES;
}



#pragma mark- JPush 推送
#pragma mark 推送初始化
-(void)initJpush:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//    if (!launchOptions) {
//        return;
//    }
    //收到通知，就进入某个页面
    if (launchOptions != nil) {
        NSLog(@"收到推送");
        /** app进程被杀死后，启动app获取推送消息 */
        NSDictionary * userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        NSLog(@"%@",userInfo);
        
    }
    // 注册apns通知
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) // iOS10
    {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        if (@available(iOS 10.0, *)) {
            entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge | UNAuthorizationOptionSound;
            [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
        } else {
            // Fallback on earlier versions
        }

    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) // iOS8, iOS9
    {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }
    else // iOS7
    {
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert) categories:nil];
    }
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:key_JPush
                          channel:CHANNEL
                 apsForProduction:IS_PRODUCTION
            advertisingIdentifier:nil];
    
    NSLog(@"%@,%d",CHANNEL,IS_PRODUCTION);
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(serviceError:)
                          name:kJPFServiceErrorNotification
                        object:nil];
}


#pragma mark 收到推送消息调用

#ifdef NSFoundationVersionNumber_iOS_9_x_Max

//------iOS10是通过JPUSHRegisterDelegate实现的回调----
// iOS10 support 应用在前台时通知回调
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
     
    }
    
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}


// iOS 10 support 程序进入后台, 通过点击推送弹出的通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
        
    }
    completionHandler();    // 系统要求执行这个方法
}
#endif


/**
 *  iOS 7..<iOS 10 后台收到通知后,点击通知后调用 或 前台收到通知时调用
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    
    // 更新显示的徽章个数
    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    badge--;
    badge = badge >= 0 ? badge : 0;
    [UIApplication sharedApplication].applicationIconBadgeNumber = badge;

    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


// iOS 6 support -- 本地通知回调函数，当应用程序在前台时调用,当应用在后台是点击通知回调
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}


#pragma mark 系统方法 与 JPush相关

/**
 程序进入前台设置bage 更改图标上显示的数字
 
 @param application
 */
- (void)applicationWillResignActive:(UIApplication *)application {
    [JPUSHService setBadge:0];//重置JPush服务器上面的badge值。如果下次服务端推送badge传"+1",则会在你当时JPush服务器上该设备的badge值的基础上＋1；
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];//apple自己的接口，变更应用本地（icon）的badge值；
}


// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    [JPUSHService registerDeviceToken:deviceToken];
    [self registerDeviceToken];
    
}

// 注册deviceToken失败，此处失败， 一般是您的环境配置或者证书配置有误
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"未授权推送");
}

#pragma mark   通知监听

- (void)networkDidSetup:(NSNotification *)notification {
    
    NSLog(@"已连接");
    
}

- (void)networkDidClose:(NSNotification *)notification {
    
    NSLog(@"未连接");
    
}

- (void)networkDidRegister:(NSNotification *)notification {
    
    NSLog(@"已注册");
}

- (void)networkDidLogin:(NSNotification *)notification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidLoginNotification object:nil];
}

- (void)serviceError:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *error = [userInfo valueForKey:@"error"];
    NSLog(@"%@", error);
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
}


#pragma mark 这部分是官方demo里面给的, 也没实现什么功能, 放着以备不时之需


- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler
{
    
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler
{
    
}

#pragma mark- 注册通知,将deviceToken传给服务器
/**
 *  注册通知
 */
-(void)registerDeviceToken{
    NSString *token = JZFetchMyDefault(@"token");
    NSString * registrationID= [JPUSHService registrationID];
    if (token) {
        [AFHttpTool postJsonDatawithUrl:@"/home/informationPush" parameters:[NSDictionary dictionaryWithObjectsAndKeys:registrationID,@"jPushRid",token,@"token", nil] success:^(id responseObject) {
            NSLog(@"----registrationID:%@",registrationID);
        } fail:^(id responseObject, NSError *error) {
            
        }];
      }
}

#pragma mark 获取系统通知权限
-(BOOL)isAllowedNotification {
    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
    if (UIUserNotificationTypeNone != setting.types) {
        return YES;
    }
    
    return NO;
}


#pragma mark- 跳转到该APP的设置中心
/**
 *  修改推送开光
 *
 *  @param status YES  打开 NO关闭
 *
 */
-(BOOL)setJpushStatus:(BOOL)status{
    
    //前往设置中心
    NSURL *url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
    return NO;
}

#pragma mark--- 检查版本更新
- (void)Checkforupdates{
    [AFHttpTool postJsonDatawithUrl:@"getVersions" parameters:@{@"versionName":[UtilCheck getVersion]} success:^(id responseObject) {
        NSLog(@"----registrationID:%@",responseObject);
        if ([[responseObject objectForKey:@"code"]integerValue]==200) {
            // 强制更新
            NSDictionary *result = [responseObject objectForKey:@"result"];
            NSString *version = [[result  objectForKey:@"versionName"]stringByReplacingOccurrencesOfString:@"." withString:@""];
             NSString *currentversion = [[THMangerTool getVersion:YES]stringByReplacingOccurrencesOfString:@"." withString:@""];
            if ([version integerValue]>[currentversion integerValue]) {
                // 主线程中更新UI
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"更新提示" message:@"App Store已经发布了新版本，请前往更新" preferredStyle:(UIAlertControllerStyleAlert)];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"前往更新" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                        //                      NSURL *updateURL = [NSURL URLWithString:@"https://appsto.re/cn/GQl5fb.i"];
                        NSURL *updateURL = [NSURL URLWithString:@"https://fir.im/elxb?"];
                        if ([[UIApplication sharedApplication] canOpenURL:updateURL]) {
                            [[UIApplication sharedApplication] openURL:updateURL];
                        };
                    }];
                    if (![[[responseObject objectForKey:@"result"]objectForKey:@"isForce"]isEqualToString:@"true"]) {
                        UIAlertAction *cancelAction2 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                            
                        }];
                        [alertVC addAction:cancelAction2];
                    }
                    [alertVC addAction:cancelAction];
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
                });
            }
        }
    } fail:^(id responseObject, NSError *error) {
        
    }];
}

@end
